<template>
  <div>
    <div class="__table">
      <el-button @click="dialogOpen('add')"
                 v-if="!search"
                 class="__table_button"><i class="el-icon-plus"></i></el-button>
      <s-table
        :table="table"
        ref="table"
        :control="false"
        :pagination="false"
        @http="tableWatch">
        <el-table-column
          fixed="right"
          align="center"
          slot="operation"
          class-name="operationMore"
          v-if="!search"
          label="操作"
          width="120">
          <template scope="s">
            <el-button type="success" icon="el-icon-edit" size="mini" @click="dialogOpen('PUT', s.row, s.$index)"
                       round></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="tableDelete(s.$index, s.row)"
                       round></el-button>
          </template>
        </el-table-column>
      </s-table>
    </div>
    <s-dialog :dialog="dialog">
      <p slot="title">
        {{dialog.title}}奖励扣款报销单
        <span v-if="dialog.title === '修改'">报销人名称：{{dialog.row.supplierName}}</span>
      </p>
      <s-form :form="formDialog" ref="formDialog">
        <el-row>
          <el-col :xs="24" :lg="{span: 11, offset: 0}">
            <el-form-item prop="supplierId" label="供应商">
              <el-select v-model="formDialog.supplierId"
                         filterable
                         remote
                         :remote-method="dialogSupplierId"
                         ref="supplierId"
                         placeholder="请选择">
                <el-option
                  v-for="item in dialog.supplierId"
                  :key="item.id"
                  :label="item.bxSupplierName + '   ' + item.bxSupplierDepartmentname"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 11, offset: 1}">
            <el-form-item prop="departmentId" label="费用所属">
              <el-cascader
                :options="DEPARTMENT.department"
                v-model="formDialog.departmentId"
                :show-all-levels="false"
                ref="departmentId"
                clearable
                filterable
                change-on-select
                :props="{
                  value: 'key',
                }"
                placeholder="所属部门"
              ></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :lg="{span: 7, offset: 0}">
            <el-form-item prop="costProject" label="项目类别">
              <el-select v-model="formDialog.costProject"
                         ref="costProject"
                         placeholder="请选择">
                <el-option
                  v-for="item in EXPENSE.rewardType"
                  :key="item.id"
                  :label="item.text"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 7, offset: 1}">
            <el-form-item prop="ascriptionCycle" label="归属周期">
              <el-date-picker
                :clearable="false"
                v-model="formDialog.ascriptionCycle"
                type="month"
                placeholder="归属周期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 7, offset: 1}">
            <el-form-item prop="type" label="项目类别">
              <el-select v-model="formDialog.type"
                         ref="type"
                         placeholder="请选择">
                <el-option
                  v-for="item in EXPENSE.category"
                  :key="item.id"
                  :label="item.text"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :xs="24" :lg="{span: 11, offset: 0}">
            <el-form-item prop="origExpenseId" label="原报销单">
              <el-select v-model="formDialog.origExpenseId"
                         filterable
                         remote
                         :remote-method="dialogOrigReimbursementId"
                         ref="origExpenseId"
                         placeholder="请选择">
                <el-option
                  v-for="item in dialog.origExpenseId"
                  :key="item.id"
                  :label="item.reimbursementCode + '   ' + item.reimbursementDate + '   ' + item.proposer + '   ' + item.costProject + '   ' + item.reimbursementProportion + '   ' + item.money + '   ' + item.reimbursementId"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="{span: 11, offset: 1}">
            <el-form-item prop="money" label="金额">
              <el-input
                type="text"
                v-model.number="formDialog.money"
                placeholder="金额"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </s-form>
      <el-button slot="footer" @click="dialogSave">保存</el-button>
    </s-dialog>
  </div>
</template>

<script>
  import {AutoVue, AutoPromise, SplitK, DeepCopy} from '~/plugins/Tools';

  let id = 0;

  /**
   * 报销单明细
   departmentId  (string, optional): 费用所属$$$true$false$false$$1$vNull,
   supplierId (string, optional): 报销人员$$$true$false$false$$1$vNull,
   costProject (string, optional): 费用项目$$$true$false$false$$1$vNull,
   ascriptionCycleName (string, optional): 归属周期$$$true$false$false$$1$vNull,
   category (string, optional): 项目类别$$$true$false$false$$1$vNull,
   origReimbursementId (string, optional): 原报销单$$$true$false$false$$1$vNull,
   money  (string, optional): 金额$$$true$false$false$$1$vNull,
   */
  function __formDialog () {
    return {
      costProject: { value: '', rule: [ 'vNull__change' ] },
      supplierId: { value: '', rule: ['vNull__change'] },
      ascriptionCycle: { value: new Date(), rule: [ 'vNull__change' ], type: 'Date' },
      type: { value: '', rule: [ 'vNull__change' ] },
      origExpenseId: { value: '', rule: [ 'vNull__change' ] },
      departmentId: { value: [], rule: [ 'vNull__change' ] },
      money: { value: '', rule: [ 'vNull', 'vNumber' ] },
    };
  }

  function tofixed (dt) {
    dt += '';
    let result;
    if (dt.indexOf('.') !== -1) {
      result = dt.substr(0, dt.indexOf('.') + 3);
    } else {
      result = dt;
    }
    return parseFloat(result);
  }

  export default AutoVue({
    name: 'rewardDeduction',
    props: {
      init: {
        type: Array,
      },
      row: {
        type: Object,
        default () {
          return {};
        },
      },
      search: {
        type: Boolean,
        default: false,
      },
    },
    data: {
      table: {
        column: [
          {'label': '费用所属', 'prop': 'departmentName', 'minWidth': '0px'},
          {
            'label': '收款方',
            'prop': 'supplierName',
            'minWidth': '0px',
          }, {'label': '归属周期',
            'prop': 'ascriptionCycle',
            formatter: (row, column) => {
              return this.a.methods.formatterTime(row[column.property || column], 22);
            },
            'minWidth': '0px'},

          {'label': '费用项目', 'prop': 'costProjectName', 'minWidth': '0px'},
          {
            'label': '项目类别',
            'prop': 'typeName',
            'minWidth': '0px',
          }, {'label': '原报销单', 'prop': 'origReimbursementCode', 'minWidth': '0px'}, {
            'label': '金额',
            'prop': 'money',
            'minWidth': '0px',
            formatter: (row, column) => {
              return SplitK(row[column.property || column]);
            },
          },
        ],
        key: 'id ',
        muti: false,
      },
      formDialog: __formDialog(),
      loanNum: {},
      dialog: {
        modal: false,
        width: '80%',
        row: {},
        index: '',
        title: '新增',
        supplierId: [],
        departmentId: [],
        origExpenseId: [],
      },
    },
    store: ['EXPENSE', 'DICTIONARY_expense', 'DEPARTMENT'],
    watch: {
      'formDialog.supplierId': function () {
        this.formDialog.origExpenseId = '';
        this.dialogOrigReimbursementId();
      },
    },
    computed: {
      maxLoanNum () {
        return this.dialog.loanNum + (this.loanNum[this.formDialog.loanId] || 0);
      },
    },
    methods: {
      tableDelete (index, row) {
        let tableRef = 'table';
        this.$confirm('您将删除该条明细。', '确认删除？', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning',
        }).then(async () => {
          this[tableRef].data.splice(index, 1);
          this.$emit('change', this.table.data);
        });
      },
      async dialogSupplierId (query = '') {
        this.dialog.supplierId = await this.post('/supplier/get', {
          name: query,
          type: 2,
        });
      },
      async dialogOrigReimbursementId (query = '') {
        let {contentList} = await this.post('/expense/seachExpenseCost', {
          supplierId: this.formDialog.supplierId || undefined,
          reimbursementCode: query,
          id: this.row.id,
          'pageNumber': 1,
          'pageSize': 100,
        });
        this.dialog.origExpenseId = contentList;
      },
      async dialogOpen (type, more, index) {
        if (type) {
          type = type.toUpperCase();
        } else return;
        await AutoPromise([
          async () => {
            if (!this.DICTIONARY_expense) {
              await this.USE('DICTIONARY_expense');
            }
          },
          async () => {
            await this.dialogSupplierId();
          },
          async () => {
            this.dialogOrigReimbursementId();
          },
          async () => {
            if (more && !more.departmentIdOld) {
              more.departmentIdOld = await this.get('/dictionaries/departmentIds/' + more.departmentId);
            }
          },
        ]);
        switch (type) {
        case 'ADD':
          this.dialog.title = '新增';
          this.formDialog.id = 0;
          break;
        case 'PUT':
          this.dialog.title = '修改';
          this.AwaitVue('formDialog', () => {
            this.formDialog = {
              ...this.formDialog,
              ...this.ObjectClone(__formDialog(), more),
            };
            this.formDialog.departmentId = [];
            let watch = this.$watch('dialog.origExpenseId', () => {
              watch();
              this.formDialog.origExpenseId = more.origExpenseId;
              this.formDialog.departmentId = more.departmentIdOld;
            });
          });
          this.dialog.row = more;
          this.dialog.index = index;
          break;
        }
        this.dialog.visible = true;
      },
      dialogSave () {
        this.VALIDATE('formDialog', option => {
          console.log('option', option);
          option.id = id++;
          option.supplierName = this.$refs.supplierId.selectedLabel.split('   ')[0];
          option.typeName = this.$refs.type.selectedLabel;
          option.costProjectName = this.$refs.costProject.selectedLabel;
          option.departmentIdOld = DeepCopy(option.departmentId);
          option.departmentId = option.departmentId[option.departmentId.length - 1];
          option.departmentName = this.$refs.departmentId.currentLabels.join('-');
          let origExpenseId = this.$refs.origExpenseId.selectedLabel.split('   ');
          option.origReimbursementCode = origExpenseId[0];
          option.reimbursementId = origExpenseId[origExpenseId.length - 1];
          if (option.money !== 0) {
            option.money = tofixed(option.money);
          }
          if (this.dialog.index === '') {
            this.table.data.push(option);
          } else {
            this.table.data.splice(this.dialog.index, 1);
            this.table.data.unshift(option);
          }
          this.$emit('change', this.table.data);
          this.dialog.dialogInit.call(this);
        });
      },
    },
    mounted: function () {
      console.log(this);
      this.USE('DEPARTMENT');
      if (this.init && this.init.length !== 0) {
        let data = [];
        this.init.forEach(item => {
          data.push({
            ...item,
            ascriptionCycle: new Date(item.ascriptionCycle),
          });
        });
        this.table.data = data;
      }
    },
  });
</script>

<style scoped lang="scss">
  .card {
    float: left;
    border-radius: 3px;
    box-shadow: 0 2px 10px 1px rgba(0, 0, 0, .1);
    height: 110px;
    width: 300px;
    margin: 15px;
    padding: 25px;
    position: relative;
    vertical-align: top;
    transition: .4s;
    cursor: pointer;
    &:hover {
      box-shadow: 0 10px 20px 1px rgba(0, 0, 0, .1);
      text-decoration: none;
    }
  }

  .card__icon {
    font-size: 24px;
    left: 28px;
    position: absolute;
    top: 25px;
    color: #20a0ff;
  }

  .card__title {
    color: #20a0ff;
    margin-top: 0;
    margin-bottom: 10px;
    margin-left: 40px;
  }

  .card__body {
    line-height: 22px;
    margin-left: 40px;
  }

  @media screen and (max-width: 800px) {
    .card {
      width: calc(100% - 80px);
    }
  }
</style>
